import Vue, { nextTick } from 'vue'
import MessageBox from './Index.vue'

const MessageBoxConstructor = Vue.extend(MessageBox)
let _messageBox = null
let mask = null

function handleRemoveEvent(instance) {
  if (instance.closeOnClickModal) {
    instance.$refs.messageBoxWrapper.removeEventListener('click', instance.handleClose)
  }
}

function showAlert(paramObj) {
  return new Promise((resolve, reject) => {
    console.log('准备创建 MessageBox 组件实例');
    if (_messageBox) {
      console.log('MessageBox 组件实例已经存在，不再创建');
      return
    }


    mask = document.createElement('div')
    mask.classList.add('message-box__mask')

    _messageBox = new MessageBoxConstructor({
      el: document.createElement('div')
    })

    Object.keys(paramObj).forEach(key => {
      if (_messageBox.hasOwnProperty(key)) {
        _messageBox[key] = paramObj[key]
      }
    })

    _messageBox.confirm = () => {
      handleRemoveEvent(_messageBox)

      _messageBox.show = false
      nextTick(() => {
        doClose()
      })
      resolve(_messageBox)
    }
    _messageBox.cancel = () => {
      handleRemoveEvent(_messageBox)

      _messageBox.show = false
      nextTick(() => {
        doClose()
      })
      reject(_messageBox)
    }

    function doClose() {
      console.log('开始 doClose');
      if (_messageBox) {
        mask.style.opacity = 0
        const itv = setTimeout(() => {
          document.body.removeChild(mask)
          mask = null
          clearTimeout(itv)
        }, 100);

        _messageBox.$destroy()
        _messageBox = null
      }
    }

    _messageBox.$on('doClose', doClose)
    
    document.body.appendChild(_messageBox.$el)
    document.body.appendChild(mask)
    requestAnimationFrame(() => {
      mask.style.opacity = 0.5
    })
  })
}

export default {
  install(Vue) {
    Vue.prototype.$T_alert = showAlert
  }
}
